package jude.java.money.batch.task;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

import jude.java.money.batch.Definition;
import jude.java.money.batch.Parameter;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 * 执行php文件
 * */
public class BatchFile extends BatchTask<String[]> {
	protected static final String BASE_PATH = "../php/";
	
	public BatchFile(Parameter<String[]> p) {
		super(p);
	}
	
	public BatchFile(int type, String... params) {
		super(Parameter.get(type, params));
	}
	
	@Override
	protected String getLabel() {
		return "FILE";
	}
	
	protected void execute(String site, String url, int group, int index) throws IOException {
		HttpClient client = getHttpClient();
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new NameValuePair("key", P.KEY));
		
		String[] updates = P.PARAMS;
		String code = getCode(updates[0]);
		params.add(new NameValuePair("value", code));
		for (int i = 1; i < updates.length; i += 2) {
			params.add(new NameValuePair(updates[i], updates[i + 1]));
		}
		PostMethod post = getPostMethod(url, params);
		shieldPost(-1, site, client, post);
	}
	
	private String getCode(String fileName) throws IOException {
		Reader in = new InputStreamReader(getClass().getResourceAsStream(BASE_PATH + fileName), "UTF-8");
		StringBuilder sb = new StringBuilder();
		char[] buff = new char[1024];
		int n;
		while ((n = in.read(buff)) != -1) {
			sb.append(buff, 0, n);
		}
		if ("<?php".equals(sb.substring(0, 5)))
			sb.delete(0, 5);
		if ("?>".equals(sb.substring(sb.length() - 2)))
			sb.delete(sb.length() - 2, sb.length());
		return sb.toString();
	}
	
	public static BatchTask<String[]> clearZencartCaches() {
		return new BatchFile(Definition.TYPE_ZENCART, "clearcache.php")
			.addFlags(Definition.CONFIG_READONLY, Definition.CONFIG_SAME_CODE);
	}
}
